# views.py
from flask import Blueprint, render_template, request, redirect, url_for, flash, abort
from flask_login import login_required, current_user, login_user, logout_user
from models import User, Photo, Vote, Comment, Favorite, Message
from forms import PhotoForm, CommentForm, SearchForm, LoginForm, RegistrationForm, ProfileForm
from datetime import datetime
from sqlalchemy import func
from extensions import db
from utils import save_image, save_avatar

# 创建主应用蓝本
main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    """首页 - 显示最新摄影作品"""
    page = request.args.get('page', 1, type=int)
    photos = Photo.query.filter_by(approved=True).order_by(Photo.created_at.desc()).paginate(
        page=page, per_page=12
    )
    return render_template('index.html', photos=photos)

@main_bp.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
    """上传作品页面"""
    form = PhotoForm()
    if form.validate_on_submit():
        # 处理文件上传
        filename, small_thumb, medium_thumb, large_thumb = save_image(form.image.data)
        
        # 创建新作品
        photo = Photo(
            title=form.title.data,
            description=form.description.data,
            filename=filename,
            thumbnail=small_thumb,
            category=form.category.data,
            author=current_user
        )
        db.session.add(photo)
        db.session.commit()
        
        flash('作品上传成功！等待管理员审核', 'success')
        return redirect(url_for('main.index'))
    
    return render_template('upload.html', form=form)

@main_bp.route('/photo/<int:photo_id>')
def photo_detail(photo_id):
    """作品详情页"""
    photo = Photo.query.get_or_404(photo_id)
    
    # 获取其他作品（同一作者的其他作品）
    other_photos = Photo.query.filter(
        Photo.user_id == photo.user_id,
        Photo.id != photo_id
    ).limit(5).all()
    
    # 检查是否已投票（需要检查用户是否已登录）
    already_voted = False
    if current_user.is_authenticated:
        already_voted = Vote.query.filter_by(user_id=current_user.id, photo_id=photo_id).first() is not None
    
    # 获取评论表单
    form = CommentForm()
    
    # 获取评论
    comments = photo.photo_comments.order_by(Comment.created_at.asc())
    
    return render_template('photo.html', 
                         photo=photo, 
                         already_voted=already_voted, 
                         comments=comments,
                         form=form,
                         other_photos=other_photos)

@main_bp.route('/vote/<int:photo_id>', methods=['POST'])
@login_required
def vote(photo_id):
    """投票功能"""
    photo = Photo.query.get_or_404(photo_id)
    
    # 检查是否已经投票
    existing_vote = Vote.query.filter_by(user_id=current_user.id, photo_id=photo_id).first()
    if existing_vote:
        flash('您已经投过票了', 'warning')
        return redirect(url_for('main.photo_detail', photo_id=photo_id))
    
    # 创建新的投票记录
    vote = Vote(user_id=current_user.id, photo_id=photo_id)
    db.session.add(vote)
    photo.vote_count += 1
    db.session.commit()
    
    flash('投票成功！', 'success')
    return redirect(url_for('main.photo_detail', photo_id=photo_id))

@main_bp.route('/favorite/<int:photo_id>', methods=['POST'])
@login_required
def favorite(photo_id):
    """收藏功能"""
    photo = Photo.query.get_or_404(photo_id)
    
    # 检查是否已经收藏
    existing_favorite = Favorite.query.filter_by(user_id=current_user.id, photo_id=photo_id).first()
    if existing_favorite:
        db.session.delete(existing_favorite)
        flash('已取消收藏', 'info')
    else:
        favorite = Favorite(user_id=current_user.id, photo_id=photo_id)
        db.session.add(favorite)
        flash('收藏成功', 'success')
    
    db.session.commit()
    return redirect(url_for('main.photo_detail', photo_id=photo_id))

@main_bp.route('/add_comment/<int:photo_id>', methods=['POST'])
@login_required
def add_comment(photo_id):
    """添加评论"""
    photo = Photo.query.get_or_404(photo_id)
    form = CommentForm()
    if form.validate_on_submit():
        comment = Comment(
            content=form.content.data,
            user_id=current_user.id,
            photo_id=photo_id
        )
        db.session.add(comment)
        db.session.commit()
        flash('评论发表成功', 'success')
    return redirect(url_for('main.photo_detail', photo_id=photo_id))

@main_bp.route('/login', methods=['GET', 'POST'])
def login():
    """登录页面"""
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(form.password.data):
            login_user(user)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(url_for('main.index'))
        else:
            flash('邮箱或密码错误', 'danger')
    return render_template('login.html', form=form)

@main_bp.route('/register', methods=['GET', 'POST'])
def register():
    """注册页面"""
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(
            username=form.username.data,
            email=form.email.data
        )
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('注册成功！请登录', 'success')
        return redirect(url_for('main.login'))
    return render_template('register.html', form=form)

@main_bp.route('/logout')
@login_required
def logout():
    """退出登录"""
    logout_user()
    flash('已退出登录', 'info')
    return redirect(url_for('main.index'))

@main_bp.route('/user/<username>')
def user_profile(username):
    """用户主页"""
    user = User.query.filter_by(username=username).first_or_404()
    photos = user.photos.filter_by(approved=True).order_by(Photo.created_at.desc()).all()
    return render_template('user.html', user=user, photos=photos)

@main_bp.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    """编辑个人资料"""
    form = ProfileForm()
    if form.validate_on_submit():
        current_user.username = form.username.data
        current_user.bio = form.bio.data
        current_user.gender = form.gender.data
        
        # 处理头像上传
        if form.avatar.data:
            avatar_filename = save_avatar(form.avatar.data)
            current_user.avatar = avatar_filename
        
        db.session.commit()
        flash('资料更新成功', 'success')
        return redirect(url_for('main.user_profile', username=current_user.username))
    
    # 填充表单数据
    form.username.data = current_user.username
    form.bio.data = current_user.bio
    form.gender.data = current_user.gender
    return render_template('edit_profile.html', form=form)

@main_bp.route('/messages')
@login_required
def messages():
    """消息中心"""
    messages = current_user.received_messages.filter_by(read=False).all()
    for msg in messages:
        msg.read = True
    db.session.commit()
    return render_template('messages.html', messages=messages)